import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
// import 'package:address_selector_for_chinese/index.dart';
// import 'package:flutter_pickers/pickers.dart';
import 'package:yysk_app/model/common_model/get_certification_type_model.dart';
import 'package:yysk_app/model/pay_model/open_wallet_info_model.dart';
import 'package:yysk_app/net/api/api_url.dart';
import 'package:yysk_app/net/api/common_api.dart';
import 'package:yysk_app/net/api/pay_url.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/nft_pages/wallet_pages/enterprise_auth/auth_audit_page.dart';
import 'package:yysk_app/pages/nft_pages/wallet_pages/wallet/wallet_page.dart';
import 'package:yysk_app/utils/js_tool.dart';
import 'package:yysk_app/widget/drop_down_widget.dart';
import 'package:oktoast/oktoast.dart';

class EnterpriseAuthController extends GetxController {
  var isAuthed = false.obs;
  // var legalPersonController = TextEditingController();
  // var idCardController = TextEditingController();
  var companyNameController = TextEditingController(); //公司名称
  var creditCodeController = TextEditingController(); //社会信用代码
  var validityController = TextEditingController(); //证件有效期
  var detailAddressController = TextEditingController(); //详细地址
  var bankCardController = TextEditingController(); //绑定银行卡号
  var bankSpaceController = TextEditingController(); //绑定选择银行支行
  var phoneContectController = TextEditingController(); //绑定联系人
  var phoneContectNameController = TextEditingController(); //绑定联系人姓名
  var phoneController = TextEditingController();
  var isLongTerm = false.obs;
  var addressText = ''.obs;
  var licenseImage = Rxn<Uint8List>();
  var loading = false.obs;
  var test = 0.obs; //不能删。有用
  final type = '2'.obs; //1个人，2企业，3个体户
  var title = '开通钱包'.obs;
  var certBeginDate = ''.obs;
  var certEndDate = ''.obs;
  var isLong = false.obs;
  var certBeginDateBank = ''.obs;
  var certEndDateBank = ''.obs;
  var isLongBank = false.obs;
   var plat = ''.obs;
  //plat
  final ImagePicker picker = ImagePicker();
  List<ChooseTypeModel> companyList = [
    ChooseTypeModel(name: '请选择', type: ''),
    ChooseTypeModel(name: '企业', type: 'ENTERPRISE'),
    ChooseTypeModel(name: '个体工商户', type: 'INDIVIDUAL_BUSINESS'),
  ];
  List<ChooseTypeModel> bankTypeList = [
    ChooseTypeModel(name: '请选择', type: ''),
    ChooseTypeModel(name: '对公', type: 'CORPORATE'),
    ChooseTypeModel(name: '对私', type: 'PERSONAL'),
  ];

  //获取个人数据
  final infoDetail = Rx<GetCertificationTypeModel?>(null);
  //企业开户信息
  final openWalletInfo = Rx<OpenWalletInfoModel>(
    OpenWalletInfoModel(
      bankAccount: BankAccount(
        accountType: "CORPORATE",
        bankCode: "",
        bankName: "",
        branch: "",
        cardNo: "",
        city: "",
        openingLicenseUrl: "",
        province: "",
      ),
      businessAddressInfo: BusinessAddressInfo(
        address: "",
        city: "",
        district: "",
        province: "",
      ),
      channel: "HUIFU",
      legalPersonInfo: LegalPersonInfo(
        legalLicenceBacktUrl: "",
        legalLicenceFrontUrl: "",
        legalPersonLicenceNo: "",
        legalPersonMobile: "",
        legalPersonName: "",
        certBeginDate: '',
        certEndDate: '',
      ),
      plat: "",
      subjectInfo: SubjectInfo(
        certNo: "",
        certUrl: "",
        certValidate: "",
        contactMobile: "",
        signName: "",
        certValidityType: "",
        certBeginDate: '',
        certEndDate: '',
      ),
    ),
  );
  // 认证完后 获取信息
  Future<void> getAutherInfo() async {
    http.netFetch<OpenWalletInfoModel>(
      PayUrl.registerDetailQuery,
      method: Method.post,
      params: {
        "plat": type.value == '2' ? 'ENTERPRISE' : 'INDIVIDUAL_BUSINESS',
        "channel": channel,
      },
      success: (r) {
        openWalletInfo.value = r.data!;
        companyNameController.text = r.data!.subjectInfo!.signName!; //公司名称
        creditCodeController.text = r.data!.subjectInfo!.certNo!; //社会信用代码
        validityController.text = r.data!.subjectInfo!.certValidate!; //证件有效期
        detailAddressController.text =
            r.data!.businessAddressInfo!.address!; //详细地址
        bankCardController.text = r.data!.bankAccount!.cardNo!; //绑定银行卡号
        bankSpaceController.text = r.data!.bankAccount!.bankName!; //绑定选择银行支行
        phoneContectController.text =
            r.data!.subjectInfo!.contactMobile!; //绑定联系人
        phoneContectNameController.text =
            r.data!.subjectInfo!.contactName!; //绑定联系人姓名
        phoneController.text = r.data!.subjectInfo!.contactMobile!;
        phoneContectNameController.text = r.data!.subjectInfo!.contactName!;//联系人名字
        if(r.data!.legalPersonInfo!.certValidityType=='1'){
          isLong.value = true;
        }else{
          isLong.value = false;
        }
         if(r.data!.subjectInfo!.certValidityType=='1'){
          isLongBank.value = true;
        
        }else{
          isLongBank.value = false;
          
        }
        certBeginDateBank.value = r.data!.subjectInfo!.certBeginDate!;
        certEndDateBank.value = r.data!.subjectInfo!.certEndDate!;
         certBeginDate.value = r.data!.legalPersonInfo!.certBeginDate!;
        certEndDate.value = r.data!.legalPersonInfo!.certEndDate!;
        return r;
      },
    );
  }

  // 加载银行数据
  Future<void> _loadBanks() async {
    try {
      final data = await rootBundle.loadString('static/json/bank_list.json');
      final jsonData = json.decode(data);
      banks.value = jsonData;
    } catch (e) {
      print("加载银行数据失败: $e");
    }
  }

  // 加载省市区数据
  Future<void> _loadCitys() async {
    try {
      final data = await rootBundle.loadString('static/json/city_list.json');
      final jsonData = json.decode(data);
      city.value = jsonData;
    } catch (e) {
      print("加载省市区数据失败: $e");
    }
  }
  String channel = "";
  @override
  void onInit() {
    super.onInit();
    channel =  (Get.arguments['channel'] ?? '') == 'DEBIT_CARD' ? 'HUIFU' : 'DIN_PAY';
    openWalletInfo.value.channel = channel;
    isAuthed.value = Get.arguments['isAuthed'];
    type.value = (Get.arguments['type']) ?? '2';
    title.value = (Get.arguments['title']) ?? '开通钱包';
    openWalletInfo.value.plat= (Get.arguments['plat']) ?? 'ENTERPRISE';


    updateUserInfo();
    // 可根据实际情况初始化已认证状态和数据
    _loadBanks();
    _loadCitys();
    if (isAuthed.value) {
      getAutherInfo();
    }
  }

  var banks = RxList<dynamic?>([]);
  var city = RxList<dynamic?>([]);
  var selectedBank = ''.obs;
  var selectedCode = ''.obs;
  void pickLicenseImage() async {
    final picker = ImagePicker();
    final picked = await picker.pickImage(source: ImageSource.gallery);
    if (picked != null) {
      licenseImage.value = await picked.readAsBytes();
    }
  }

  void pickValidityDate() async {
    DateTime? picked = await showDatePicker(
      // locale: Locale('zh', 'CN'),
      context: Get.context!,
      initialDate: DateTime.now(),
      firstDate: DateTime(2000),
      lastDate: DateTime(2100),
    );
    if (picked != null) {
      validityController.text =
          '${picked.year}${picked.month > 10 ? picked.month : "0${picked.month}"}${picked.day >= 10 ? picked.day : "0${picked.day}"}';
    }
  }

  void setLongTerm(bool value) {
    isLongTerm.value = value;
    if (value) {
      validityController.text = '99990909';
    } else {
      validityController.clear();
    }
  }

  void submitAuth() async {
    // TODO: 实现提交认证逻辑
    consoleLog('请输入公司名称=${companyNameController.text}');
    consoleLog('统一社会信用代码=${creditCodeController.text}');
    consoleLog('请输入公司详细地址=${detailAddressController.text}');
    consoleLog('请输入银行卡号=${bankCardController.text}');
    consoleLog('请输入银行支行=${phoneController.text}');
    consoleLog('银行预留手机号=不用');
    consoleLog('联系人电话=${phoneContectController.text}');
    consoleLog('联系人电话名字=${phoneContectNameController.text}');

    openWalletInfo.value.subjectInfo?.certNo = creditCodeController.text;
    if (openWalletInfo.value.subjectInfo?.certNo == '') {
      showToast('请输入营业执照证件号');
      return;
    }
    // openWalletInfo.value.subjectInfo?.certValidate = validityController.text;
    // if (openWalletInfo.value.subjectInfo?.certValidate == '') {
    //   showToast('请选择证件有效期');
    //   return;
    // }
    //
    openWalletInfo.value.subjectInfo?.certValidityType =
        (isLongBank.value == true ? '1' : '0');
    openWalletInfo.value.subjectInfo?.certBeginDate = certBeginDateBank.value;
    openWalletInfo.value.subjectInfo?.certEndDate = certEndDateBank.value;
    openWalletInfo.value.legalPersonInfo?.certBeginDate = certBeginDate.value;
    openWalletInfo.value.legalPersonInfo?.certEndDate = certEndDate.value;
    openWalletInfo.value.legalPersonInfo?.certValidityType =
        (isLong.value == true ? '1' : '0');

    openWalletInfo.value.subjectInfo?.signName = companyNameController.text;
    if (openWalletInfo.value.subjectInfo?.signName == '') {
      showToast('请输入公司名称');
      return;
    }
    openWalletInfo.value.subjectInfo?.contactName =
        phoneContectNameController.text;
    if (openWalletInfo.value.subjectInfo?.contactName == '') {
      showToast('请输入联系人姓名');
      return;
    }
    openWalletInfo.value.subjectInfo?.contactMobile =
        phoneContectController.text;
    if (openWalletInfo.value.subjectInfo?.contactMobile == '') {
      showToast('请输入联系人手机号');
      return;
    }

    // openWalletInfo.value.bankAccount?.cardNo = bankCardController.text;
    // if (openWalletInfo.value.bankAccount?.cardNo == '') {
    //   showToast('请输入银行卡号');
    //   return;
    // }

    openWalletInfo.value.businessAddressInfo?.address =
        detailAddressController.text;
    if (openWalletInfo.value.businessAddressInfo?.address == '') {
      showToast('请输入详细地址');
      return;
    }

    http.netFetch<GetCertificationTypeModel>(
      PayUrl.registerApply,
      method: Method.post,
      params: openWalletInfo.toJson(),
      success: (r) {
        infoDetail.value = r.data;
        Get.offNamed(AuthAuditPage.path);
        return r;
      },
    );
  }

  @override
  void onClose() {
    // legalPersonController.dispose();
    // idCardController.dispose();
    companyNameController.dispose();
    creditCodeController.dispose();
    validityController.dispose();
    detailAddressController.dispose();
    bankCardController.dispose();
    bankSpaceController.dispose();
    phoneContectController.dispose();
    phoneController.dispose();
    super.onClose();
  }

  //获取认证信息
  Future<dynamic> updateUserInfo() async {
    final res = http.netFetch<GetCertificationTypeModel>(
      CommonApi.getCertificationType,
      method: Method.post,
      success: (r) {
        infoDetail.value = r.data;
        return r;
      },
    );
    return res;
  }

  //获取类型
  String _getMimeType(String filename) {
    final ext = filename.split('.').last.toLowerCase();
    switch (ext) {
      case 'png':
        return 'image/png';
      case 'jpg':
      case 'jpeg':
        return 'image/jpeg';
      case 'gif':
        return 'image/gif';
      case 'webp':
        return 'image/webp';
      default:
        return 'application/octet-stream'; // 更通用的二进制类型
    }
  }

  //获取数据
  void uploadImage(String type) async {
    try {
      final XFile? image = await picker.pickImage(source: ImageSource.gallery);
      // 2. 获取腾讯云上传地址
      await getUploadUrl(type).then((res) {
        //  _uploadToTencentCloud(res, File(image!.path));
        uploadToTencentCloud(res, image!).then((r) {
          String url = res.split('?')[0];
          if (type == '1') {
            //营业执照
            consoleLog('营业执照赋值');
            openWalletInfo.value.subjectInfo?.certUrl = url;
          } else if (type == '2') {
            //许可证
            consoleLog('许可证');
            openWalletInfo.value.bankAccount?.openingLicenseUrl = url;
          } else if (type == '3') {
            //身份证国徽面
            consoleLog('身份证国徽面');
            openWalletInfo.value.legalPersonInfo?.legalLicenceBacktUrl = url;
          } else if (type == '4') {
            //身份证人像面
            consoleLog('身份证人像面');
            openWalletInfo.value.legalPersonInfo?.legalLicenceFrontUrl = url;
          }
          test.value++;
        });
        debugPrint('腾讯云上传地址: $res');
      });
    } catch (e) {
      debugPrint('图片处理出错：${e.toString()}');
    }
  }

  //获取上传图片链接
  Future<String> getUploadUrl(String type) async {
    int timestampInSeconds = DateTime.now().millisecondsSinceEpoch ~/ 1000;
    try {
      final response = await http.netFetch<dynamic>(
        ApiUrl.getUploadUrl,
        method: Method.post,
        params: {'key': '$timestampInSeconds.png'},
      );
      consoleLog('${response?.code}==code   type==${type}');
      if (response?.code == 200) {
        // controller.avatarImg.value = response?.data.split('?')[0];
        // debugPrint('渠道图片地址: ${controller.avatarImg.value}');
        return response?.data;
      }
      return response?.data;
    } catch (e) {
      debugPrint('获取上传地址出错: ${e.toString()}');
      rethrow; // 重新抛出异常，让外层处理
    }
  }

  //上传图片
  Future<String> uploadToTencentCloud(String url, XFile file) async {
    try {
      final fileBytes = await file.readAsBytes();

      // 创建独立的Dio实例，避免全局配置污染
      final dio = Dio(
        BaseOptions(
          responseType: ResponseType.plain, // 明确接收文本响应
          validateStatus: (status) => true, // 处理所有状态码
        ),
      );

      final response = await dio
          .put<String>(
            // 指定返回类型为String
            url,
            data: fileBytes,
            options: Options(
              headers: {
                'Content-Type': _getMimeType(file.name),
                'Content-Length': fileBytes.length.toString(),
              },
            ),
          )
          .then((res) {
            //  debugPrint('上传响应原始数据222: ${res}========');
          });
      // 根据状态码判断成功，而不是响应体内容
      if (response == null) {
        // 更新用户信息

        return url;
      }
      // 处理其他状态码
      throw DioException(
        requestOptions: response.requestOptions,
        response: response,
        error: '上传失败，状态码：${response.statusCode}',
      );
    } on DioException catch (e) {
      // 统一错误处理
      debugPrint('上传错误详情: ${e.message}');
      if (e.response != null) {
        debugPrint('错误响应头: ${e.response?.headers}');
        debugPrint('错误响应体: ${e.response?.data}');
      }
      showToast('上传失败: ${e.message ?? "未知错误"}');
      return '';
    }
  }

  //控制器回显赋值
  getChooseValue() {}
  void pickValidityDate1(int type) async {
    DateTime? picked = await showDatePicker(
      context: Get.context!,
      initialDate: DateTime.now(),
      firstDate: DateTime(1900),
      lastDate: DateTime(2100),
      initialEntryMode: DatePickerEntryMode.input,
    );
    if (picked != null) {
      if (type == 0) {
        certBeginDate.value =
            '${picked.year}${picked.month > 10 ? picked.month : "0${picked.month}"}${picked.day > 10 ? picked.day : "0${picked.day}"}';
      } else {
        certEndDate.value =
            '${picked.year}${picked.month > 10 ? picked.month : "0${picked.month}"}${picked.day > 10 ? picked.day : "0${picked.day}"}';
      }
    }
  }

  void pickValidityDate2(int type) async {
    DateTime? picked = await showDatePicker(
      context: Get.context!,
      initialDate: DateTime.now(),
      firstDate: DateTime(1900),
      lastDate: DateTime(2100),
      initialEntryMode: DatePickerEntryMode.input,
    );
    if (picked != null) {
      if (type == 0) {
        certBeginDateBank.value =
            '${picked.year}${picked.month > 10 ? picked.month : "0${picked.month}"}${picked.day > 10 ? picked.day : "0${picked.day}"}';
      } else {
        certEndDateBank.value =
            '${picked.year}${picked.month > 10 ? picked.month : "0${picked.month}"}${picked.day > 10 ? picked.day : "0${picked.day}"}';
      }
    }
  }
}
